import pygame
import math

class Weapon:
    """武器类，管理火尖枪的投掷和返回逻辑"""
    def __init__(self, sprite_path, throw_speed=10, throw_duration=0.5, cooldown=0.5):
        """初始化武器
        Args:
            sprite_path (str): 武器图片路径
            throw_speed (int): 投掷速度
            throw_duration (float): 投掷持续时间
            cooldown (float): 冷却时间
        """
        self.sprite = pygame.image.load(sprite_path).convert_alpha()  # 加载武器图片
        self.original_sprite = self.sprite  # 保存原始图片用于旋转后恢复
        self.rect = self.sprite.get_rect()  # 获取武器矩形区域
        self.state = "ready"  # 武器状态：准备, 投掷中, 返回中
        self.throw_speed = throw_speed  # 投掷速度
        self.throw_duration = throw_duration  # 投掷持续时间
        self.base_cooldown = cooldown * 60  # 将冷却时间转换为帧数
        self.current_cooldown = 0  # 当前冷却时间
        self.cooldown = self.base_cooldown  # 实际冷却时间
        self.throw_start_time = 0  # 投掷开始时间
        self.return_start_time = 0  # 返回开始时间
        self.throw_vector = (0, 0)  # 投掷方向向量
        self.return_vector = (0, 0)  # 返回方向向量
        self.x = 0  # 当前x坐标
        self.y = 0  # 当前y坐标
        self.owner = None  # 武器持有者（玩家）

    def start_throw(self, start_pos, target_pos):
        """开始投掷武器
        Args:
            start_pos (tuple): 投掷起始位置 (x, y)
            target_pos (tuple): 投掷目标位置 (x, y)
        """
        if self.state == "ready" and self.current_cooldown <= 0:
            self.state = "throwing"  # 设置为投掷状态
            self.throw_start_time = pygame.time.get_ticks() / 1000  # 记录投掷开始时间
            self.throw_vector = self._calculate_vector(start_pos, target_pos)  # 计算投掷方向
            self._rotate_weapon(target_pos)  # 旋转武器指向目标

    def update(self, current_time):
        """更新武器状态
        Args:
            current_time (float): 当前时间
        """
        if self.owner and self.state == "ready":
            # 跟随持有者位置
            self.x = self.owner.x + self.owner.rect.width // 2 - self.rect.width // 2
            self.y = self.owner.y + self.owner.rect.height // 2 - self.rect.height // 2
        elif self.state == "throwing":
            progress = (current_time - self.throw_start_time) / self.throw_duration
            if progress < 1:
                self.x += self.throw_vector[0] * self.throw_speed  # 沿投掷方向移动
                self.y += self.throw_vector[1] * self.throw_speed
            else:
                self.state = "returning"  # 投掷结束后进入返回状态
                self.return_start_time = current_time
                if self.owner:
                    self.return_vector = self._calculate_vector(
                        (self.x, self.y),
                        (self.owner.x + self.owner.rect.width // 2,
                         self.owner.y + self.owner.rect.height // 2)
                    )  # 计算返回方向

        elif self.state == "returning":
            progress = (current_time - self.return_start_time) / self.throw_duration
            if progress < 1:
                self.x += self.return_vector[0] * self.throw_speed  # 沿返回方向移动
                self.y += self.return_vector[1] * self.throw_speed
            else:
                self.state = "ready"  # 返回结束后进入准备状态
                self.current_cooldown = self.cooldown  # 重置冷却时间
                self.sprite = self.original_sprite  # 恢复原始图片

        # 根据持有者的攻击速度更新冷却时间
        if self.owner:
            self.cooldown = int(self.base_cooldown / self.owner.attack_speed)
             
        if self.current_cooldown > 0:
            self.current_cooldown -= 1  # 冷却时间递减

        self.rect.topleft = (self.x, self.y)  # 更新武器位置

    def _calculate_vector(self, start, target):
        """计算从起点到目标点的单位向量
        Args:
            start (tuple): 起点坐标 (x, y)
            target (tuple): 目标坐标 (x, y)
        Returns:
            tuple: 单位向量 (x, y)
        """
        dx = target[0] - start[0]
        dy = target[1] - start[1]
        distance = math.hypot(dx, dy)
        if distance == 0:
            return (0, 0)
        return (dx/distance, dy/distance)

    def _rotate_weapon(self, target_pos):
        """旋转武器使其指向目标位置
        Args:
            target_pos (tuple): 目标位置 (x, y)
        """
        dx = target_pos[0] - self.x
        dy = target_pos[1] - self.y
        angle = math.degrees(math.atan2(-dy, dx)) - 45  # 计算旋转角度，初始角度为-45度
        orig_rect = self.sprite.get_rect()
        rot_image = pygame.transform.rotate(self.sprite, angle)  # 旋转图片
        rot_rect = orig_rect.copy()
        rot_rect.center = rot_image.get_rect().center
        self.sprite = rot_image.subsurface(rot_rect).copy()  # 更新武器图片

    def draw(self, screen):
        """绘制武器
        Args:
            screen (pygame.Surface): 游戏屏幕
        """
        screen.blit(self.sprite, (self.x, self.y))  # 在指定位置绘制武器